package com.lyfei.yd.admin.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyfei.yd.common.core.domain.AjaxResult;
import com.lyfei.yd.common.exception.CustomException;
import com.lyfei.yd.domain.dto.PageQueryDto;
import com.lyfei.yd.domain.entity.Theme;
import com.lyfei.yd.domain.entity.ThemeSpu;
import com.lyfei.yd.service.ThemeService;
import com.lyfei.yd.service.ThemeSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/theme")
public class ThemeController {
    @Autowired
    private ThemeService themeService;

    @Autowired
    private ThemeSpuService themeSpuService;

    @PostMapping("/add")
    public AjaxResult add(@RequestBody Theme theme) {
        themeService.save(theme);
        return AjaxResult.success();
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody Theme theme) {
        if(theme.getId() == null || themeService.getById(theme.getId()) == null) {
            throw new CustomException("主题不存在");
        }

        // 更新主题
        themeService.updateById(theme);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        if(themeService.getById(id) == null) {
            throw new CustomException("主题不存在");
        }

        // 删除主题
        themeService.removeById(id);
        return AjaxResult.success();
    }

    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable Long id) {
        return AjaxResult.success(themeService.getById(id));
    }

    @GetMapping("/page")
    public AjaxResult page(PageQueryDto dto) {
        return AjaxResult.success(themeService.page(new Page<>(dto.getCurrent(), dto.getPageSize())));
    }

    @GetMapping("/getSpuListByTheme")
    public AjaxResult getSpuListByTheme(@RequestParam Long id) {
        return AjaxResult.success(themeService.getSpuListByThemeId(id));
    }

    @GetMapping("/getAvailableSpuList")
    public AjaxResult getAvailableSpuList(@RequestParam Long id) {
        return AjaxResult.success(themeService.getAvailableSpuList(id));
    }

    @PostMapping("/add/spu")
    public AjaxResult addThemeSpu(@RequestBody ThemeSpu themeSpu) {
        themeSpuService.save(themeSpu);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/spu/{id}")
    public AjaxResult deleteThemeSpu(@PathVariable Long id) {
        themeSpuService.removeById(id);
        return AjaxResult.success();
    }
}
